<template>
  <div>
    <van-form>
      <van-field name="isbn"
                 label="isbn">
        <template #input>
          <van-field v-model="userBook.isbn"
          placeholder="可以通过isbn自动填写哦"
          :rules="[{require: false,message: '图书isbn'}]"></van-field>
          <van-button class="isbnack" @click="isbnAck(userBook.isbn)">确定</van-button>
        </template>
      </van-field>
      <van-field
          v-model='userBook.title'
          name="书名"
          label="书名"
          :rules="[{require:true,message:'请填写书名'}]"/>
      <van-field
      v-model="userBook.author"
      name="作者"
      label="作者"
      placeholder="作者"/>
      <van-field
      class="book-gist"
      type="textarea"
      v-model="userBook.gist"
      name="简介"
      label="简介"
      placeholder="来简单描述一下吧"/>
      <van-field name="计价规则" label="计价规则">
        <template #input>
        <van-checkbox-group v-model="userBook.priceRules" direction="horizontal">
            <van-checkbox name="1" shape="square">按天</van-checkbox>
<!--            <van-checkbox name="2" shape="square">按月</van-checkbox>-->
<!--            <van-checkbox name="3" shape="square">卖出</van-checkbox>-->
        </van-checkbox-group>
`     </template>
      </van-field>
      <van-field name="dayPrice" label="每天价格"
                 v-model="userBook.dayPrice" placeholder="每天多少钱"/>
      <van-field name="number" label="数量">
        <template #input>
          <van-stepper v-model="userBook.number"/>
        </template>
      </van-field>
      <van-field name="uploader" label="上传图片">
        <template #input>
          <van-uploader v-model="fileList" :after-read="afterRead"/>
        </template>
      </van-field>
     <van-button round block type="info"
                  @click="mySubmit">提交</van-button>
    </van-form>

  </div>
</template>
<script>

  import Vue from 'vue';
  import {Form, Stepper, Uploader, Checkbox, CheckboxGroup, Dialog} from 'vant';
  import {ApiService} from "@/axios/apiService";

  Vue.use(Form);
  Vue.use(Stepper);
  Vue.use(Uploader);
  Vue.use(Checkbox);
  Vue.use(CheckboxGroup);
  Vue.use(Dialog);
  export default {
    data() {
      return {
        userBook: {
           userId:1,
           title:'',
           author:'',
           number:1,
           gist:'',
           isbn:'',
           imgs: [],
           priceRules:[],
           buyPrice: '',
           dayPrice: '',
           mouthPrice: '',
         },
        fileList: []
      };
    },
    mounted() {
      this.ifLogin()
    },
    methods:{
      async afterRead(file) {
          console.log("this.afterRead()")
          //初试化
          let OSS = require('ali-oss');


          let client = new OSS({
            region: 'oss-cn-chengdu',
            accessKeyId: 'LTAI5tKbKKZo33r8EpDqgGWH',
            accessKeySecret: 'wPzuRowwhcB7brUAwDfTcEIo8hAnBI',
            bucket: 'jingzai-pethome',
          });
          //此时可以自行将文件上传至服务器
          try {
            // 填写Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
            // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
            console.log(new Date().getTime())
            var ti = new Date().getTime()
            let result = await client.put('/img/' + ti + '.jpg', file.file)
            console.log(result)
            console.log("图片链接：" + result.url)
            this.userBook.imgs.push(result.url)
          } catch (e) {
            console.log(e);
          }
      },
      mySubmit() {
        //添加用户图书数据
        const addBook = new ApiService("/userBook/add");
        this.userBook.userId=addBook.getCookie("userId")
        console.log(this.userBook)
        addBook.post(this.userBook).then(res=> {
          if(res.data.code == 200) {
            Dialog.alert({
              message:'添加成功'
            }).then (() => {
              this.userBook = null
            })
          }
        })
      },
      //通过isnb获取数据
      isbnAck(isbn) {
        const api = new ApiService("/book/addBookByIsbn")
        api.getParams({isbn:isbn}).then(res=>{
          if(res.data.code == 200) {
            this.userBook = res.data.data;
            this.userBook.imgs = []
            this.userBook.imgs.push(res.data.data.img)
            //添加图片信息
            var imgurl = res.data.data.img;
            console.log(imgurl)
            this.fileList.push({
              url:imgurl
            });
            this.userBook.imgs.push(imgurl);
            console.log( "imgs"+this.userBook.imgs)
          }
        })
      },
      // 判断是否登录
      ifLogin() {
        const api =new ApiService("/user");
        var userId = api.getCookie("userId");
        if(userId == null || userId == "") {
          console.log("token is " + userId)
          this.$router.push('/login')
        }else {
          console.log(this.token)
        }},
    },
  };
</script>
<style>
.isbnack {
  float: right;
}
</style>
